package com.hotacorp.opencloud.gateway.keyresolver;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.hotacorp.opencloud.common.commdata.Constants;
import com.hotacorp.opencloud.gateway.feign.TokenInfoFeignClient;

import reactor.core.publisher.Mono;

/**
 * 用户决定者
 * @author lwg
 *
 */
public class UserKeyResolver implements KeyResolver {
	public static final String BEAN_NAME = "userKeyResolver";
	@Autowired
	@Lazy
	private TokenInfoFeignClient tokenInfoFeignClient;
	@Override
	public Mono<String> resolve(ServerWebExchange exchange) {
		JSONObject userinf = (JSONObject)exchange.getAttributes().get(Constants.USER_INFO);
		if (userinf == null) {
			List<String> aaa1 = exchange.getRequest().getQueryParams().getOrDefault("access_token", Collections.emptyList());
			List<String> aaa2 = exchange.getRequest().getHeaders().getOrDefault(HttpHeaders.AUTHORIZATION, Collections.emptyList());
			if (!aaa1.isEmpty() || !aaa2.isEmpty()) {
				String access_token = "";
				if (!aaa2.isEmpty()) {
					access_token = aaa2.get(0).replace("Bearer", "").trim();
				} else {
					access_token = aaa1.get(0);
				}
				String infostr = tokenInfoFeignClient.getTokenInfo(access_token);
				if (infostr != null && StringUtils.contains(infostr, "\"client_id\":\"") && StringUtils.contains(infostr, "\"user_id\":") && StringUtils.startsWith(infostr, "{") && StringUtils.endsWith(infostr, "}")) {
					userinf = JSONObject.parseObject(infostr);
					exchange.getAttributes().put(Constants.USER_INFO, userinf);
				}
			}
		}
    	if (userinf == null) {
            return Mono.empty();
    	} else {
    		return Mono.just(userinf.getString(userinf.getString(Constants.USER_ID)));
    	}
	}
}

